<template>
  <basic-dialog :visible="show"
                  title="工单报工"
                  min-width="760px"
                  :titleTips="`[${form.id ? form.id : '--'}]`"
                  :isShowInnerLoading = 'loading'>
      <q-form @submit="submit" @reset="reset" class="dialog-content" greedy>
        <div class="row" style="padding:20px 10px 10px">
          <div class="col-3 text-ellipsis">
            产品：{{ form.materialName ? form.materialName : '--' }}({{ form.materialNumber ? form.materialNumber : '--' }})
            <q-tooltip>{{ form.materialName ? form.materialName : '--' }}({{ form.materialNumber ? form.materialNumber : '--' }})</q-tooltip>
          </div>
          <div class="col-3 text-ellipsis">
            订单编号：{{ form.orderNumber ? form.orderNumber : '--' }}
            <q-tooltip>{{ form.orderNumber ? form.orderNumber : '--' }}</q-tooltip>
          </div>
          <div class="col-3 text-ellipsis">
            批次编号：{{ form.orderBatch ? form.orderBatch : '--' }}
            <q-tooltip>{{ form.orderBatch ? form.orderBatch : '--' }}</q-tooltip>
          </div>
          <div class="col-3 text-ellipsis">
            加工工序：{{ (form.processSort && form.processName) ? `${form.processSort}-${form.processName}` : '--' }}
            <q-tooltip>{{ (form.processSort && form.processName) ? `${form.processSort}-${form.processName}` : '--'}}</q-tooltip>
          </div>
          <div class="col-3 text-ellipsis">
            加工设备：{{ form.deviceName ? form.deviceName : '--' }}
            <q-tooltip>{{ form.deviceName ? form.deviceName : '--' }}</q-tooltip>
          </div>
          <div class="col-3 text-ellipsis">
            派工班次：{{ form.shiftName ? form.shiftName : '--' }}
            <q-tooltip>{{ form.shiftName ? form.shiftName : '--' }}</q-tooltip>
          </div>
          <div class="col-3 text-ellipsis">
            作业人员：{{ form.operator ? form.operator : '--' }}
            <q-tooltip>{{ form.operator ? form.operator : '--' }}</q-tooltip>
          </div>
          <div class="col-3 text-ellipsis">
            派工数量：{{ form.jobCount }}
          </div>
          <div class="col-3 text-ellipsis">
            已报数量：{{ Number(form.finishedCount || 0)}}
          </div>
          <div class="col-3 text-ellipsis">
            待报数量：{{ Math.round((Number(form.jobCount) - Number(form.finishedCount)) * 1000) / 1000 | isLtZero }}
          </div>
        </div>
        <div style="padding: 0 20px 20px; margin-top: 0">
          <q-card-section class="dialog-title bg-primary" style="border-top-left-radius: 6px; border-top-right-radius: 6px; display: flex;justify-content: space-between">
            <div class="text-center text-white">{{ '报工操作 ' }}<span style="font-size: 14px">(最多增加五条)</span></div>
            <a style="color: #fff;cursor: pointer;font-size: 18px" class="iconfont icontubiao-50" :class="{'disable' : tableData.length === 5}" @click="addRow">
              <q-tooltip anchor="bottom middle" self="center middle">
                添加报工记录
              </q-tooltip>
            </a>
          </q-card-section>
          <q-table
            v-if="deviceTypeCode !== 'void'"
            color="primary"
            :data="tableData" :columns="columns"
            row-key="id"
            class="myTable scroll"
            style="margin: 0"
            :pagination.sync="pagination" :hide-bottom="!!tableData.length">
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td key="index" :props="props">
                  {{ tableData.indexOf(props.row) + 1 }}
                </q-td>
                <q-td key="shift" :props="props" style="padding-top: 10px">
                  <q-select
                    @input="getOperator(form.deviceId, props.row.shift, props.row)"
                    style="width: 150px"
                    v-model="props.row.shift"
                    :options="shiftOptions"
                    :rules="[
                      val => !!val || '请选择加工班次',
                      () => myRule()
                    ]"
                    dense
                    options-dense
                    emit-value
                    map-options
                    outlined
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                    <template v-slot:before>
                      <label class="text-right" style="font-size: 14px;color: #333">
                        <span class="text-red">*</span>
                      </label>
                    </template>
                  </q-select>
                </q-td>
                <q-td key="operator" :props="props" style="padding-top: 10px;padding-bottom: 20px;line-height: 32px">
                  {{ props.row.operator }}
                </q-td>
                <q-td key="jobQuantity" :props="props" style="padding-top: 10px">
                  <q-input
                    @input="judgeCompleted"
                    ref="jobCount"
                    style="width: 150px"
                    v-model="props.row.jobQuantity"
                    dense
                    outlined
                    :rules="[
                      val =>  /^\d+(\.\d)?$/.test(val) && val > 0 || '请输入数字(支持一位小数)',
                      val => judgeCount(val) || '本次报工数量不能大于待报数量'
                    ]"
                  >
                    <template v-slot:before>
                      <label class="text-right" style="font-size: 14px;color: #333">
                        <span class="text-red">*</span>
                      </label>
                    </template>
                  </q-input>
                </q-td>
                <q-td class="operations"  style="width: 20px">
                  <div class="btn-group">
                    <table-btn btn-type="delete" :disable="tableData.length === 1" @click="deleteRow(props.row)"/>
                  </div>
                </q-td>
              </q-tr>
            </template>
          </q-table>

          <q-table
            v-else
            color="primary"
            :data="tableData" :columns="columns"
            row-key="id"
            class="myTable scroll"
            style="margin: 0"
            :pagination.sync="pagination"  :hide-bottom="!!tableData.length">
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td key="index" :props="props">
                  {{ tableData.indexOf(props.row) + 1 }}
                </q-td>
                <q-td key="shift" :props="props" style="padding-top: 10px">
                  <q-select
                    style="width: 150px"
                    v-model="props.row.shift"
                    :options="shiftOptions"
                    :rules="[
                      val => (val !== undefined && val !== null) || '请选择班次'
                    ]"
                    dense
                    options-dense
                    emit-value
                    map-options
                    outlined
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                    <template v-slot:before>
                      <label class="text-right" style="font-size: 14px;color: #333">
                        <span class="text-red">*</span>
                      </label>
                    </template>
                  </q-select>
                </q-td>
                <q-td key="operator" :props="props" style="padding-top: 10px">
                  <q-select
                    style="width: 150px"
                    v-model="props.row.operatorId"
                    :options="operatorOptions"
                    :rules="[
                      val => (val !== undefined && val !== null) || '请选择操作人员'
                    ]"
                    dense
                    options-dense
                    emit-value
                    map-options
                    outlined
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                    <template v-slot:before>
                      <label class="text-right" style="font-size: 14px;color: #333">
                        <span class="text-red">*</span>
                      </label>
                    </template>
                  </q-select>
                </q-td>
                <q-td key="jobQuantity" :props="props" style="padding-top: 10px">
                  <q-input
                    @input="judgeCompleted"
                    ref="jobCount"
                    style="width: 150px"
                    v-model="props.row.jobQuantity"
                    dense
                    outlined
                    :rules="[
                      val =>  /^\d+(\.\d)?$/.test(val) && val > 0 || '请输入数字(支持一位小数)',
                      val => judgeCount(val) || '报工数量不能大于待报数量'
                    ]"
                  >
                    <template v-slot:before>
                      <label class="text-right" style="font-size: 14px;color: #333">
                        <span class="text-red">*</span>
                      </label>
                    </template>
                  </q-input>
                </q-td>
                <q-td class="operations"  style="width: 20px">
                  <div class="btn-group">
                    <table-btn btn-type="delete" :disable="tableData.length === 1" @click="deleteRow(props.row)"/>
                  </div>
                </q-td>
              </q-tr>
            </template>
          </q-table>
          <q-input class="margin-t-20" outlined v-model="remark" type="textarea" counter autogrow maxlength="100">
            <template v-slot:before>
              <label class="text-right name full-width" style="font-size: 14px">备注:</label>
            </template>
          </q-input>
        </div>
        <q-separator />
        <div class="dialog-footer text-center margin-t-10">
          <div style="position: absolute; left: 30px; bottom: 5px" v-show="false">
            <q-checkbox left-label disable v-model="isWorkCompleted" label="是否完工:" />
          </div>
          <q-btn outline label="取消" color="primary" @click="$emit('close')" class="q-mr-md"/>
          <q-btn unelevated label="确认" color="primary" type="submit"/>
        </div>
      </q-form>
    </basic-dialog>
</template>

<script>
import { getWorkShopId, getShifts, getOperator, getDepartmentUsers } from 'src/boot/job/process-order'
import { mapGetters } from 'vuex'
export default {
  name: 'work-order-completed',
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  filters: {
    isLtZero (val) {
      return val > 0 ? val : 0
    }
  },
  data () {
    return {
      loading: false,
      deviceTypeCode: null,
      promiseResolvers: null,
      isWorkCompleted: false,
      form: [],
      pagination: {
        rowsPerPage: 0
      },
      tableData: [{
        index: 0,
        shift: '',
        operator: '',
        jobQuantity: 1,
        operatorId: null
      }],
      columns: [
        { name: 'index', label: '序号', align: 'left', field: 'index' },
        { name: 'shift', label: '实际加工班次', field: 'shift', align: 'left' },
        { name: 'operator', label: '实际加工人', field: 'operator', align: 'left' },
        { name: 'jobQuantity', label: '报工数量', field: 'jobQuantity', align: 'left' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ],
      operatorOptions: [], // 实际加工人源数据
      shiftOptions: [], // 班制源数据
      remark: ''
    }
  },

  methods: {
    // 编辑填充表格
    assignment (val) {
      this.loading = true
      this.deviceTypeCode = val.deviceTypeCode
      this.shiftOptions = []
      this.form = val
      this.remark = ''
      const ids = [val.deviceId]
      this.judgeCompleted()
      getWorkShopId(ids).then(res => {
        return res.data[val.deviceId]
      }).then(data => {
        if (data) {
          getShifts(data).then(res => {
            if (res.data.length > 0) {
              res.data.forEach(o => {
                this.shiftOptions.push({
                  value: o.id,
                  label: o.name
                })
                if (val.shiftId === o.id) {
                  this.tableData[0].shift = val.shiftId
                  if (this.deviceTypeCode !== 'void') {
                    // 若设备类型不为void(非机加工工序，查询人机绑定实际操作人)
                    this.getOperator(val.deviceId, val.shiftId, this.tableData[0])
                  } else {
                    // 否则获取与登陆人同班组的非机加工操作工
                    this.getOperatorOptions()
                  }
                  this.form.shiftId = o.id
                }
              })
            } else {
              this.form.shiftId = null
              this.loading = false
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    },

    // 获取操作员
    getOperator (deviceId, shiftId, row) {
      const index = this.tableData.indexOf(row)
      this.promiseResolvers = getOperator(deviceId, shiftId)
      this.promiseResolvers.then(res => {
        this.tableData[index].operator = Object.values(res.data)[0]
        this.tableData[index].operatorId = Object.keys(res.data)[0]
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取非机加工同部门所有人
    async getOperatorOptions () {
      this.operatorOptions = []
      let res = await getDepartmentUsers(this.userInfo.user_id, true)
      this.loading = false
      this.operatorOptions = res.data.map(o => {
        return {
          value: o.id,
          label: o.name
        }
      })
    },

    // 异步校验实际加工人
    myRule () {
      return new Promise(resolve => {
        this.promiseResolvers.then(res => {
          resolve(Object.values(res.data).length > 0 || '当前班次未进行人机绑定')
        })
      })
    },

    // 验证完工数量
    judgeCount () {
      let ret = false
      // const unfinishedQuantity = this.form.jobCount - this.form.finishedCount
      const unfinishedQuantity = new this.$Big(this.form.jobCount).minus(this.form.finishedCount)
      let NumberOfReports = 0
      this.tableData.forEach(o => {
        NumberOfReports = NumberOfReports + Number(o.jobQuantity)
      })
      console.log(`unfinishedQuantity:${unfinishedQuantity}`)
      console.log(`NumberOfReports:${NumberOfReports}`)
      unfinishedQuantity >= NumberOfReports ? ret = true : ret = false
      return ret
    },

    // 判断是否完工
    judgeCompleted () {
      // const unfinishedQuantity = this.form.jobCount - this.form.finishedCount
      const unfinishedQuantity = Math.round((Number(this.form.jobCount) - Number(this.form.finishedCount)) * 1000) / 1000
      let NumberOfReports = 0
      this.tableData.forEach(o => {
        NumberOfReports = NumberOfReports + Number(o.jobQuantity)
      })
      if (NumberOfReports >= unfinishedQuantity) {
        this.isWorkCompleted = true
      } else {
        this.isWorkCompleted = false
      }
    },

    // 清空表单
    reset () {
      this.isWorkCompleted = false
      this.tableData = [{
        index: 0,
        shift: '',
        operator: '',
        jobQuantity: 1
      }]
    },

    // 提交表单
    submit () {
      this.loading = true
      this.$emit('submit', this.form, this.tableData, this.isWorkCompleted, this.remark)
    },
    hideLoading () {
      this.loading = false
    },
    // 添加表格行
    addRow () {
      if (this.tableData.length < 5) {
        this.tableData.push({
          index: this.tableData.length + 1,
          shift: '',
          operator: '',
          jobQuantity: 1
        })
      }
      this.judgeCompleted()
    },

    // 删除表格行
    deleteRow (row) {
      const index = this.tableData.indexOf(row)
      if (this.tableData.length > 1) {
        this.tableData.splice(index, 1)
      }
      this.judgeCompleted()
    }
  }
}
</script>

<style scoped lang="stylus">
  /deep/ .q-select__dropdown-icon {
    width 24px
    height 24px
    font-size 24px
    color rgba(0, 0, 0, .54)
  }
  .disable{
    opacity .6 !important
  }
  .col-3{
    padding 0 10px
    margin-bottom 10px
  }
</style>
